<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">MBTI人格测试</h1>
      <p class="page-subtitle">探索你的人格类型，了解真实的自己</p>
    </div>

    <!-- 测试类型选择 -->
    <div class="test-types-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" v-for="testType in testTypes" :key="testType.testTypeId">
          <el-card class="test-type-card" shadow="hover" @click="selectTestType(testType)">
            <div class="test-type-content">
              <div class="test-type-icon">
                <el-icon><User /></el-icon>
              </div>
              <h3 class="test-type-name">{{ testType.typeName }}</h3>
              <p class="test-type-description">{{ testType.description }}</p>
              <div class="test-type-info">
                <span class="info-item">
                  <el-icon><Document /></el-icon>
                  {{ testType.questionCount }} 题
                </span>
                <span class="info-item" v-if="testType.timeLimit">
                  <el-icon><Timer /></el-icon>
                  {{ testType.timeLimit }} 分钟
                </span>
              </div>
              <el-button type="primary" class="start-test-btn" @click="startTest">开始测试</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 用户信息输入对话框 -->
    <el-dialog
      title="开始测试"
      v-model="userInfoDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="userInfo" :rules="userInfoRules" ref="userInfoFormRef" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="userInfo.userName" placeholder="请输入您的姓名（可选）"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="userInfo.userEmail" placeholder="请输入您的邮箱（可选）"></el-input>
        </el-form-item>
        <div class="dialog-info">
          <p v-if="isLoggedIn"><el-icon><InfoFilled /></el-icon> 您已登录，测试结果将自动保存到您的历史记录</p>
          <p v-else><el-icon><InfoFilled /></el-icon> 您未登录，可以进行匿名测试，但结果不会保存</p>
          <p><el-icon><InfoFilled /></el-icon> 填写个人信息可以帮助您更好地管理测试记录</p>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userInfoDialogVisible = false">取消</el-button>
          <el-button v-if="!isLoggedIn" @click="goToLogin" type="info">登录后测试</el-button>
          <el-button type="primary" @click="startTest" :loading="startTestLoading">开始测试</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 测试历史 -->
    <div class="test-history-section" v-if="isLoggedIn && testHistory.length > 0">
      <h2>我的测试历史</h2>
      <el-table :data="testHistory" style="width: 100%">
        <el-table-column prop="testTypeName" label="测试类型" width="200"></el-table-column>
        <el-table-column prop="personalityType" label="人格类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.personalityType" type="success">{{ scope.row.personalityType }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="测试时间" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '1'" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.status === '0'" type="warning">进行中</el-tag>
            <el-tag v-else type="info">已放弃</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '1'"
              size="small"
              type="primary"
              link
              @click="viewResult(scope.row.recordId)"
            >
              查看结果
            </el-button>
            <el-button
              v-if="scope.row.status === '0'"
              size="small"
              type="primary"
              link
              @click="continueTest(scope.row.recordId)"
            >
              继续测试
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- MBTI介绍 -->
    <div class="mbti-intro-section">
      <h2>关于MBTI</h2>
      <el-row :gutter="20">
        <el-col :xs="24" :md="12">
          <div class="intro-content">
            <h3>什么是MBTI？</h3>
            <p>
              MBTI（Myers-Briggs Type Indicator）是一种人格类型指标，基于心理学家卡尔·荣格的心理类型理论开发。
              它通过四个维度来描述人格类型：
            </p>
            <ul>
              <li><strong>外向(E) vs 内向(I)</strong>：能量来源和注意力方向</li>
              <li><strong>感觉(S) vs 直觉(N)</strong>：信息收集方式</li>
              <li><strong>思考(T) vs 情感(F)</strong>：决策制定方式</li>
              <li><strong>判断(J) vs 知觉(P)</strong>：生活方式偏好</li>
            </ul>
          </div>
        </el-col>
        <el-col :xs="24" :md="12">
          <div class="intro-content">
            <h3>16种人格类型</h3>
            <p>
              MBTI将人格分为16种不同的类型，每种类型都有其独特的特征、优势和发展方向。
              了解自己的人格类型可以帮助您：
            </p>
            <ul>
              <li>更好地了解自己的行为模式</li>
              <li>改善人际关系和沟通方式</li>
              <li>选择适合的职业发展方向</li>
              <li>提升个人成长和自我认知</li>
            </ul>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { getTestTypes, startTest as startTestApi, getUserTestHistory } from "@/api/mbti/test"
import { parseTime } from '@/utils/ruoyi'
import { ElMessage } from 'element-plus'
import { User, Document, Timer, InfoFilled } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const testTypes = ref([])
const userInfoDialogVisible = ref(false)
const selectedTestType = ref(null)
const userInfo = reactive({
  userName: '',
  userEmail: ''
})
const userInfoRules = {
  userEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}
const startTestLoading = ref(false)
const testHistory = ref([])
const isLoggedIn = ref(false)
const userInfoFormRef = ref()

// 生命周期
onMounted(() => {
  getTestTypesList()
  checkLoginStatus()
  if (isLoggedIn.value) {
    getUserTestHistoryList()
  }
})

// 方法
const getTestTypesList = async () => {
  try {
    const response = await getTestTypes()
    testTypes.value = response.data
  } catch (error) {
    ElMessage.error('获取测试类型失败')
  }
}

const checkLoginStatus = () => {
  isLoggedIn.value = userStore.token !== undefined && userStore.token !== ''
}

const selectTestType = (testType) => {
  selectedTestType.value = testType
  userInfoDialogVisible.value = true
}

const startTest = async () => {
  if (!userInfoFormRef.value) return
  
  try {
    await userInfoFormRef.value.validate()
    startTestLoading.value = true
    
    const data = {
      testTypeId: selectedTestType.value.testTypeId,
      userName: userInfo.userName || '匿名用户',
      userEmail: userInfo.userEmail || ''
    }
    
    const response = await startTestApi(data)
    ElMessage.success('测试开始成功')
    userInfoDialogVisible.value = false
    startTestLoading.value = false
    
    // 存储测试信息到localStorage，供未登录用户使用
    if (!isLoggedIn.value) {
      const testInfo = {
        recordId: response.data.recordId,
        testTypeId: selectedTestType.value.testTypeId,
        testTypeName: selectedTestType.value.typeName,
        startTime: new Date().toISOString(),
        isAnonymous: true
      }
      localStorage.setItem('anonymousMbtiTest', JSON.stringify(testInfo))
    }
    
    // 跳转到测试页面
    router.push({
      path: '/mbti/test',
      query: {
        recordId: response.data.recordId,
        testTypeId: selectedTestType.value.testTypeId
      }
    })
  } catch (error) {
    startTestLoading.value = false
    if (error !== false) { // 不是表单验证错误
      ElMessage.error('开始测试失败')
    }
  }
}

const getUserTestHistoryList = async () => {
  try {
    const response = await getUserTestHistory()
    testHistory.value = response.data
  } catch (error) {
    // 未登录或获取失败，忽略错误
  }
}

const viewResult = (recordId) => {
  router.push({
    path: '/mbti/result',
    query: { recordId: recordId }
  })
}

const continueTest = (recordId) => {
  router.push({
    path: '/mbti/test',
    query: { recordId: recordId }
  })
}

const goToLogin = () => {
  // 保存当前选择的测试类型到localStorage
  if (selectedTestType.value) {
    localStorage.setItem('pendingMbtiTest', JSON.stringify({
      testTypeId: selectedTestType.value.testTypeId,
      typeName: selectedTestType.value.typeName,
      returnUrl: '/mbti'
    }))
  }
  userInfoDialogVisible.value = false
  router.push('/login')
}

// 将方法暴露给模板
defineExpose({})
</script>

<style lang="scss" scoped>
.page-header {
  text-align: center;
  margin-bottom: 40px;
  
  .page-title {
    font-size: 2.5em;
    color: #409EFF;
    margin-bottom: 10px;
  }
  
  .page-subtitle {
    font-size: 1.2em;
    color: #666;
    margin: 0;
  }
}

.test-types-container {
  margin-bottom: 60px;
}

.test-type-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.test-type-content {
  text-align: center;
  padding: 20px;
  
  .test-type-icon {
    font-size: 3em;
    color: #409EFF;
    margin-bottom: 15px;
  }
  
  .test-type-name {
    font-size: 1.5em;
    margin-bottom: 10px;
    color: #333;
  }
  
  .test-type-description {
    color: #666;
    margin-bottom: 20px;
    line-height: 1.6;
  }
  
  .test-type-info {
    margin-bottom: 20px;
    
    .info-item {
      display: inline-block;
      margin: 0 10px;
      color: #999;
      font-size: 0.9em;
      
      .el-icon {
        margin-right: 5px;
      }
    }
  }
  
  .start-test-btn {
    width: 120px;
  }
}

.dialog-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 15px;
  
  p {
    margin: 5px 0;
    color: #666;
    font-size: 0.9em;
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 5px;
      color: #409EFF;
    }
  }
}

.test-history-section {
  margin-bottom: 60px;
  
  h2 {
    margin-bottom: 20px;
    color: #333;
  }
}

.mbti-intro-section {
  background: #f8f9fa;
  padding: 40px;
  border-radius: 8px;
  
  h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
  }
  
  .intro-content {
    h3 {
      color: #409EFF;
      margin-bottom: 15px;
    }
    
    p {
      line-height: 1.8;
      color: #666;
      margin-bottom: 15px;
    }
    
    ul {
      padding-left: 20px;
      
      li {
        line-height: 1.8;
        color: #666;
        margin-bottom: 8px;
      }
    }
  }
}
</style>
